package cn.ztr.ymcc.service.impl;

import cn.ztr.ymcc.CourseDOC;
import cn.ztr.ymcc.domain.*;
import cn.ztr.ymcc.dto.CourseDTO;
import cn.ztr.ymcc.dto.MessageDTO;
import cn.ztr.ymcc.feign.SearchFeign;
import cn.ztr.ymcc.mapper.*;
import cn.ztr.ymcc.result.JsonResult;
import cn.ztr.ymcc.service.ICourseService;
import cn.ztr.ymcc.util.AssertUtil;
import cn.ztr.ymcc.util.StrUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ztr
 * @since 2023-02-27
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private CourseDetailMapper courseDetailMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseResourceMapper courseResourceMapper;
    @Autowired
    private CourseSummaryMapper courseSummaryMapper;
    @Autowired
    private CourseTypeMapper courseTypeMapper;
    @Autowired
    private SearchFeign searchFeign;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    /**
     * 添加课程
     * 课程  课程详情 课程营销信息 课程资源 课程教师关联信息 课程数据统计
     *
     * @param
     */
    @Override
    @Transactional
    public void save(CourseDTO courseDTO) {
        Course course = courseDTO.getCourse();
        CourseDetail courseDetail = courseDTO.getCourseDetail();
        CourseMarket courseMarket = courseDTO.getCourseMarket();
        List<String> zipResources = courseDTO.getZipResources();
        List<Long> teacharIds = courseDTO.getTeacharIds();

        //1 添加课程信息
        //查找教师名称
        List<Teacher> teachers = teacherMapper.selectBatchIds(teacharIds);
        List<String> teacherNames = teachers.stream().map(Teacher::getName).collect(Collectors.toList());
        course.setTeacherNames(String.join(",", teacherNames));
        baseMapper.insert(course);

        //2 添加课程详情
        courseDetail.setId(course.getId());
        courseDetailMapper.insert(courseDetail);

        //3 添加课程营销
        courseMarket.setId(course.getId());
        courseMarketMapper.insert(courseMarket);

        //4 添加课程资源
        //courseResource.setCourseId(course.getId());
        CourseResource cr = new CourseResource();
        cr.setCourseId(course.getId()).setType(0);
        for (String resource : zipResources) {
            cr.setResources(resource);
            courseResourceMapper.insert(cr);
        }

        //5 添加课程教师关联信息
        baseMapper.insertCourseTeacher(course.getId(), teacharIds);

        //6 添加课程数据汇总
        CourseSummary courseSummary = new CourseSummary();
        courseSummary.setId(course.getId());
        courseSummary.setId(course.getId());
        courseSummaryMapper.insert(courseSummary);

    }

    /**
     * 获取 课程详情 课程营销信息 课程资源 课程教师关联信息 课程数据统计 的信息
     * @param id
     * @return
     */
    @Override
    public JsonResult getOtherDetail(Long id) {
        //查询课程
        Course course = baseMapper.selectById(id);
        //查询课程详情
        CourseDetail courseDetail = courseDetailMapper.selectById(id);
        //查询课程资源
        List<CourseResource> courseResources = courseResourceMapper.selectList(new QueryWrapper<CourseResource>().eq("course_id", id));
        //查询课程讲师
        List<Long> teacherIds = baseMapper.selectTeachersById(id);
        //查询课程营销
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        //查询课程类型
        CourseType courseType = courseTypeMapper.selectOne(new QueryWrapper<CourseType>().eq("id", course.getCourseTypeId()));
        //将查询的数据进行封装
        Map<String, Object> map = new HashMap<>();
        map.put("courseDetail",courseDetail);
        map.put("courseType",courseType);
        map.put("courseResources",courseResources);
        map.put("courseMarket",courseMarket);
        map.put("teacherIds",teacherIds);
        return JsonResult.me(map);
    }

    /**
     * 根据id修改课程
     * @param courseDTO
     */
    @Override
    @Transactional
    public void updateById(CourseDTO courseDTO) {
        Course course = courseDTO.getCourse();
        CourseDetail courseDetail = courseDTO.getCourseDetail();
        CourseMarket courseMarket = courseDTO.getCourseMarket();
        List<String> zipResources = courseDTO.getZipResources();
        List<Long> teacharIds = courseDTO.getTeacharIds();
        //baseMapper.updateById()
        //修改课程
        baseMapper.updateById(course);

        //修改课程详情
        courseDetailMapper.updateById(courseDetail);

        //修改课程营销
        courseMarketMapper.updateById(courseMarket);

        //修改课程教师关系
        baseMapper.deleteCourseTeacher(course.getId());
        baseMapper.insertCourseTeacher(course.getId(), teacharIds);

        //修改课程资源
        courseResourceMapper.delete(new QueryWrapper<CourseResource>().eq("course_id",course.getId()));
        CourseResource cr = new CourseResource();
        cr.setCourseId(course.getId()).setType(0);
        for (String resource : zipResources) {
            cr.setResources(resource);
            courseResourceMapper.insert(cr);
        }
    }

    /**
     * 课程上架
     * @param courses
     * @return
     */
    @Override
    public JsonResult onLineCourse(List<Course> courses) {

        //1 如果数据中有已上架课程,就不能上架
        List<Course> collect = courses.stream().filter(course -> course.getStatus() == 1).collect(Collectors.toList());
        AssertUtil.isTrue(collect==null||collect.isEmpty(),"存在已上架课程,请重新选择");

        //2 获得coursedoc对象
        ICourseService proxy = (ICourseService) AopContext.currentProxy();
        List<CourseDOC> courseDOCList = proxy.getCourseDOCList(courses);

        //3 添加到es中
        JsonResult jsonResult = searchFeign.saveBatch(courseDOCList);
        if (!jsonResult.getSuccess())
            return JsonResult.error("课程上架失败");
        //4 推送上架信息
        sendMessage(courseDOCList);

        return JsonResult.me();
    }

    /**
     * 将course批量转化为coursedoc
     * @param courses
     * @return
     */
    @Transactional
    public List<CourseDOC> getCourseDOCList(List<Course> courses) {
        ArrayList<CourseDOC> courseDOCs = new ArrayList<>();
        for (Course course : courses) {

            //1 修改课程的状态并添加上线时间
            course.setStatus(1);
            course.setOnlineTime(new Date());
            baseMapper.updateById(course);

            CourseDOC courseDOC = new CourseDOC();
            //2 添加课程消息到doc对象
            BeanUtils.copyProperties(course, courseDOC);
            //2.1 添加类别名称
            CourseType courseType = courseTypeMapper.selectById(course.getCourseTypeId());
            courseDOC.setCourseTypeName(courseType.getName());
            //2.2 添加开课,结课,上线时间
            courseDOC
                    .setStartTime(course.getStartTime().getTime())
                    .setEndTime(course.getEndTime().getTime())
                    .setOnlineTime(course.getOnlineTime().getTime());

            //3 添加课程详情到doc对象
            CourseDetail courseDetail = courseDetailMapper.selectById(course.getId());
            BeanUtils.copyProperties(courseDetail, courseDOC);

            //4 添加课程营销情况到doc对象
            CourseMarket courseMarket = courseMarketMapper.selectById(course.getId());
            BeanUtils.copyProperties(courseMarket, courseDOC);
            courseDOC.setPrice(courseMarket.getPrice().doubleValue());
            courseDOC.setPriceOld(courseMarket.getPriceOld().doubleValue());

            //5 添加课程汇总信息到doc对象
            CourseSummary courseSummary = courseSummaryMapper.selectById(course.getId());
            BeanUtils.copyProperties(courseSummary, courseDOC);

            //添加到集合中
            courseDOCs.add(courseDOC);

        }
        return courseDOCs;
    }


    /**
     * 推送课程上架信息
     * @param courseDOCList
     * @return
     */
    public boolean sendMessage(List<CourseDOC> courseDOCList){

        for (CourseDOC courseDOC : courseDOCList) {
            MessageDTO messageDTO = new MessageDTO();
            List<MessageDTO.Eamil> eamils = messageDTO.getEamils();
            List<MessageDTO.Sms> smsss = messageDTO.getSms();
            List<MessageDTO.Station> stations = messageDTO.getStations();
            messageDTO.setTitle("课程上架信息");

            //添加基础信息
            String content = "尊敬的用户您好,"+courseDOC.getName()+"刚刚发布,快去抢前排吧!";
            messageDTO.setContent(content);

            for (int i = 0; i < 2; i++) {
                //1 封装邮件信息
                Long aLong = Long.valueOf(StrUtils.getRandomString(6));
                MessageDTO.Eamil eamil = new MessageDTO.Eamil();
                eamil.setCopyto("1");
                eamil.setEmail("123@qq.com");
                eamil.setUserId(aLong);
                eamils.add(eamil);

                //2 封装短信信息
                MessageDTO.Sms sms = new MessageDTO.Sms();
                sms.setIp("重庆");
                sms.setPhone("12332332");
                sms.setUserId(aLong);
                smsss.add(sms);

                //3 封装站内信信息
                MessageDTO.Station station = new MessageDTO.Station();
                station.setType("1");
                station.setIsread(0);
                station.setUserId(aLong);
                stations.add(station);
            }
            producer(messageDTO);
        }
        return true;
    }

    /**
     * 推送课程上架信息
     * mq生产者
     * @param messageDTO
     */
    public void producer(MessageDTO messageDTO){
        /*Message<String> build = MessageBuilder.withPayload(JSON.toJSONString(messageDTO)).build();
        rocketMQTemplate.sendOneWay("ztr_topic:email",build);

        rocketMQTemplate.send("ztr_topic:sms",build);

        rocketMQTemplate.sendOneWay("ztr_topic:station",build);*/
    }

    /**
     * 根据课程id获取讲师信息
     * @param id
     * @return
     */
    @Override
    public JsonResult getTeacherCourseId(Long id) {
        List<Teacher> teachers = baseMapper.getTeacherCourseId(id);
        return JsonResult.me(teachers);
    }

}
